package com.link.base.base.autoconfig.autoconfig.service;
/*
created By:huanganbang
created:2017
comments:本程序用于处理自动配置相关的文件
* */

import com.link.base.base.autoconfig.autoconfig.model.LnkInnerField;
import com.link.base.base.autoconfig.autoconfig.model.LnkInnerObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AutoLoadProject {
    private static final Logger logger = LogManager.getLogger(AutoLoadProject.class);

    public static void main(String[] args) throws Exception {
        ReadAllJSPFileAndGetModel();
        // testsql();
    }

    private static void testsql() throws DocumentException {
        Init();// 初始化
        String path = "C:/app/workspace/java/link-crm/src/main/java/"
                + "com/hand/base/common/dao/mybatis/sqlMap/AnnounceMapper.xml";
        String temp = getsqlFromMapperId(path, "queryAllAnnounceListPage");
        // System.out.println(temp);
        // System.out.println("-----------------------start--------------------------");
        ParseSQL(temp);// 分析sql文件
    }

    protected static Map<String, String> basemodelinfo;
    protected static Map<String, Object> modelInfo;
    protected static Map<String, Object> jspModelInfo;
    protected static Map<String, String> jspModelKeyword;
    protected static String Folder;
    protected static String jspfile;
    protected static List<LnkInnerField> finalLF;
    protected static List<LnkInnerObject> finalHeader;
    protected static Map<String, String> sql_tbmap;        // sql解析过程中分析表关系
    protected static Map<String, String> sql_field;
    protected static Map<String, String> sql_fieldlov;
    protected static Map<String, String> sql_where;

    public String GetOneWhere(String tbalias, Boolean last) {
        String temp = "";
        if (last) {
            Iterator it = sql_where.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                String tableName = key.toString();
                String tableVaue = value.toString();
                temp += (tableVaue + " AND ");
            }
            temp = temp.replaceAll("\\s+AND\\s+$", "");
            return temp;
        } else {
            Iterator it = sql_where.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                String tableName = key.toString();
                String tableVaue = value.toString();
                Pattern p1 = Pattern.compile("[^a-zA-Z]+" + tbalias + ".",
                        Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                Matcher m1 = p1.matcher(tableVaue);
                if (m1.find()) {
                    sql_where.remove(tableName);
                    return tableVaue;
                }
            }
            it = sql_where.entrySet().iterator();
            if (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                String tableName = key.toString();
                String tableVaue = value.toString();
                sql_where.remove(tableName);
                return tableVaue;
            }
        }
        return temp;
    }

    private static final Pattern ADDTOSQLFIELD_PATTERN =
            Pattern.compile("[\\s\\S]*[\\s]+([\\S]+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static void AddToSqlField(String aStr, String bStr) {
        // //System.out.println("a is:" + a);
        // //System.out.println("b is:" + b);
        aStr = aStr.trim();
        bStr = bStr.trim();
        if (bStr.contains("(") || bStr.contains(")") || bStr.contains("'")) {
            bStr = "";
        }
//        Pattern p1 = Pattern.compile("[\\s\\S]*[\\s]+([\\S]+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher m1 = ADDTOSQLFIELD_PATTERN.matcher(aStr);
        boolean fund = m1.find();
        if (fund) {
            if (m1.groupCount() > 0) {
                aStr = m1.group(1);
            }
        }
        sql_field.put(aStr.toUpperCase(), bStr.toUpperCase());
    }

    private static final Pattern PATTERN1 = Pattern.compile("SELECT([\\s\\S]*)FROM([\\s\\S]*?)WHERE([\\s\\S]*)",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static final Pattern PATTERN2 = Pattern.compile("ORDER BY ([\\s\\S]+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static final Pattern PATTERN3 = Pattern.compile("SELECT([\\s\\S]*)FROM([\\s\\S]*)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static final Pattern PATTERN4 = Pattern.compile("ORDER BY ([\\s\\S]+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static final Pattern PATTERN5 = Pattern.compile("TO_CHAR[\\s]*\\(([\\s\\S]*?),[\\s\\S]*?\\)([\\s\\S]*?\\s*?[\\S]*?)[,|$]",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static final Pattern PATTERN6 = Pattern.compile(
            "GET_LOV_NAME[\\s]*\\([\\s\\S]*?,([\\s\\S]*?),([\\s\\S]*?)\\)([\\s\\S]*?\\s*?[\\S]*?)[,|$]",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static final Pattern PATTERN7 = Pattern.compile("[\\s]*([\\S]*?)[\\s]+([\\s\\S]*?)[,|$]");

    private static final Pattern PATTERN8 = Pattern.compile("[\\s]*([\\S]*?)[\\s]*?[,|$]");

    private static final Pattern PATTERN9 = Pattern.compile("[\\s]*([\\S]+)[\\s]+([\\S]*?)[,|\\s]");

    private static final Pattern PATTERN10 = Pattern.compile("[\\s]*([\\s\\S]*?) and", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    public static void ParseSQL(String sql) {
        // System.out.println(sql);
        String regex = "(?i)<if[\\s\\S]*?</if>";
        sql = sql.replaceAll(regex, "");
        sql = sql.replaceAll("/\\*[\\s\\S]*?\\*/", "");
        sql = sql.replaceAll("--[\\s\\S]*?\n", "");
        sql = sql.replaceAll("(?m)^\\s*$" + System.lineSeparator(), "");
        sql = sql.replaceAll("(?i)select", "SELECT");
        sql = sql.replaceAll("(?i)from", "FROM");
        sql = sql.replaceAll("(?i)where", "WHERE");
        sql = sql.replaceAll("(?i)order by", "ORDER BY");
        sql = sql.replaceAll("(?i)to_char\\(", "TO_CHAR(");
        sql = sql.replaceAll("(?i)get_lov_name\\(", "GET_LOV_NAME(");
        // System.out.println(sql);
        String selectString = "";
        String fromString = "";
        String whereString = "";
        String orderString = "";
        Pattern p1 = PATTERN1;/*Pattern.compile("SELECT([\\s\\S]*)FROM([\\s\\S]*?)WHERE([\\s\\S]*)",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);*/
        Matcher m1 = PATTERN1.matcher(sql);
        boolean fund = m1.find();
        if (fund) {
            if (m1.groupCount() > 2) {
                selectString = m1.group(1).trim() + ",";
                fromString = m1.group(2);
                whereString = m1.group(3);
                whereString = whereString.replaceAll("1[\\s]*=[\\s]*1", "");
//                Pattern p2 = Pattern.compile("ORDER BY ([\\s\\S]+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                Matcher m2 = PATTERN2.matcher(whereString);
                while (m2.find()) {
                    if (m2.groupCount() > 0) {
                        orderString = m2.group(1);
                        // System.out.println(orderString);
                    }
                }
                whereString = whereString.replaceAll("(?i)ORDER BY[\\s\\S]*", "");
            }
        }
        if (!fund) {
            p1 = PATTERN3;//Pattern.compile("SELECT([\\s\\S]*)FROM([\\s\\S]*)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
            m1 = p1.matcher(sql);
            if (m1.find() && m1.groupCount() > 1) {
                selectString = m1.group(1).trim() + ",";
                fromString = m1.group(2);
                whereString = "";
                whereString = whereString.replaceAll("1[\\s]*=[\\s]*1", "");
                Pattern p2 = PATTERN4;//Pattern.compile("ORDER BY ([\\s\\S]+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                Matcher m2 = p2.matcher(fromString);
                if (m2.find()) {
                    if (m2.groupCount() > 0) {
                        orderString = m2.group(1);
                        // System.out.println(orderString);
                    }
                    fromString = fromString.replaceAll("(?i)ORDER BY[\\s\\S]*", "");
                }
            }
        }
        // 先按照正则提取的方式进行提取。
        String col = "";
        String field = "";
        String lov = "";
        String coltb = "";
        String f1 = selectString;
        // //System.out.println("===================================211111");
        // //System.out.println(f1);
        if (f1.toUpperCase().contains("TO_CHAR")) {
            Pattern p2 = PATTERN5;/*Pattern.compile("TO_CHAR[\\s]*\\(([\\s\\S]*?),[\\s\\S]*?\\)([\\s\\S]*?\\s*?[\\S]*?)[,|$]",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);*/
            Matcher m2 = p2.matcher(f1);
            while (m2.find()) {
                if (m2.groupCount() > 1) {
                    String temp1 = m2.group(1);
                    String temp2 = m2.group(2);
                    String temp3 = temp2.replaceAll("(?i)[\\s]*as[\\s]+", "");
                    if (temp1.contains(".")) {
                        coltb = temp1.substring(0, temp1.indexOf("."));
                        col = temp1.substring(temp1.indexOf("."), temp1.length());
                    } else {
                        coltb = "T1";
                        col = temp1;
                    }
                    field = temp3;
                    if (!"".equals(field) && !"".equals(col)) {
                        AddToSqlField(field.trim().toUpperCase(),
                                coltb.trim().toUpperCase() + col.trim().toUpperCase());
                    }
                }
            }
            f1 = f1.replaceAll("(?i)TO_CHAR[\\s]*\\(([\\s\\S]*?),[\\s\\S]*?\\)([\\s\\S]*?\\s*?[\\S]*?)[,|$]", "");
        }
        // //System.out.println("===================================2111112");
        // //System.out.println(f1);
        if (f1.toUpperCase().contains("GET_LOV_NAME")) {
            Pattern p2 = PATTERN6;/*Pattern.compile(
                    "GET_LOV_NAME[\\s]*\\([\\s\\S]*?,([\\s\\S]*?),([\\s\\S]*?)\\)([\\s\\S]*?\\s*?[\\S]*?)[,|$]",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);*/
            Matcher m2 = p2.matcher(f1);
            while (m2.find()) {
                if (m2.groupCount() > 1) {
                    String temp2 = m2.group(2);
                    String temp3 = m2.group(3);
                    temp3 = temp3.replaceAll("(?i)[\\s]*as[\\s]+", "");
                    if (temp2.contains(".")) {
                        coltb = temp2.substring(0, temp2.indexOf("."));
                        col = temp2.substring(temp2.indexOf("."), temp2.length());
                    } else {
                        coltb = "T1.";
                        col = temp2;
                    }
                    String temp1 = m2.group(1);
                    field = temp3;
                    lov = temp1;
                    AddToSqlField(field.trim().toUpperCase(), coltb.trim().toUpperCase() + col.trim().toUpperCase());
                    if (!"".equals(lov)) {
                        sql_fieldlov.put(field.trim().toUpperCase(), lov.trim().replace("'", ""));
                    }
                }
            }
        }
        f1 = f1.replaceAll(
                "(?i)GET_LOV_NAME[\\s]*\\([\\s\\S]*?,([\\s\\S]*?),([\\s\\S]*?)\\)([\\s\\S]*?\\s*?[\\S]*?)[,|$]", "");
        Pattern p2 = PATTERN7;//Pattern.compile("[\\s]*([\\S]*?)[\\s]+([\\s\\S]*?)[,|$]");
        Matcher m2 = p2.matcher(f1);
        while (m2.find()) {
            if (m2.groupCount() > 1) {
                String temp2 = m2.group(1);
                String temp3 = m2.group(2).replaceAll("(?i)[\\s]*as[\\s]+", "");
                if (temp2.contains(".")) {
                    coltb = temp2.substring(0, temp2.indexOf("."));
                    col = temp2.substring(temp2.indexOf("."), temp2.length());
                } else {
                    coltb = "T1";
                    col = temp2;
                }
                field = temp3;
                AddToSqlField(field.trim().toUpperCase(), coltb.trim().toUpperCase() + col.trim().toUpperCase());
            }
        }
        p2 = PATTERN8;//Pattern.compile("[\\s]*([\\S]*?)[\\s]*?[,|$]");
        m2 = p2.matcher(f1);
        while (m2.find()) {
            if (m2.groupCount() > 0) {
                String temp2 = m2.group(1);
                if (temp2.contains(".")) {
                    coltb = temp2.substring(0, temp2.indexOf("."));
                    col = temp2.substring(temp2.indexOf("."), temp2.length());
                } else {
                    coltb = "T1";
                    col = temp2;
                }
                field = col;
                if (!sql_field.containsKey(field.trim().toUpperCase())) {
                    AddToSqlField(field.trim().toUpperCase(), coltb.trim().toUpperCase() + col.trim().toUpperCase());
                }
            }
        }
        p2 = PATTERN9;//Pattern.compile("[\\s]*([\\S]+)[\\s]+([\\S]*?)[,|\\s]");
        m2 = p2.matcher(fromString);
        while (m2.find()) {
            if (m2.groupCount() > 1) {
                // System.out.println(m2.group(0));
                String temp2 = m2.group(1);
                String temp3 = m2.group(2);
                if ("".equals(temp3)) {
                    temp3 = "T1";
                }
                sql_tbmap.put(temp3.trim().toUpperCase(), temp2.trim().toUpperCase());
            }
        }
        p2 = PATTERN10;//Pattern.compile("[\\s]*([\\s\\S]*?) and", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        m2 = p2.matcher(whereString + " and");
        while (m2.find()) {
            if (m2.groupCount() > 0) {
                String temp2 = m2.group(1);
                sql_where.put(temp2.trim(), temp2.trim());
            }
        }
        Iterator it = sql_tbmap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            String tableName = key.toString();
            String tableVaue = value.toString();
            // System.out.println(tableName + "---" + tableVaue);
        }
        // System.out.println("end sql_tbmap");
        it = sql_field.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            String tableName = key.toString();
            String tableVaue = value.toString();
            // System.out.println(tableName + "---" + tableVaue);
        }
        // System.out.println("end sql_field");
        it = sql_fieldlov.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            String tableName = key.toString();
            String tableVaue = value.toString();
            // System.out.println(tableName + "---" + tableVaue);
        }
        // System.out.println("end sql_fieldlov");
        it = sql_where.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            String tableName = key.toString();
            String tableVaue = value.toString();
            // System.out.println(tableName + "---" + tableVaue);
        }
        // System.out.println("end sql_where");
        // System.out.println(whereString);
    }

    public static void Init() {
        basemodelinfo = new HashMap<String, String>();
        jspModelKeyword = new HashMap<String, String>();
        modelInfo = new HashMap<String, Object>();
        jspModelInfo = new HashMap<String, Object>();
        Folder = "C://app/workspace/java/link-crm/src/main/java/com/hand/";
        jspfile = "C://app/workspace/java/link-crm/src/main/webapp/portal/";
        finalLF = new ArrayList<LnkInnerField>();
        finalHeader = new ArrayList<LnkInnerObject>();
        sql_tbmap = new HashMap<String, String>();
        sql_field = new HashMap<String, String>();
        sql_fieldlov = new HashMap<String, String>();
        sql_where = new HashMap<String, String>();
    }

    private static void printHeader() {
        System.out.println("=============About finalHeader===============");
        for (LnkInnerObject row : finalHeader) {
            if (!"".equals(row.getAttr07()) && row.getAttr07() != null) {
                // continue;
            }
            Field[] fields = row.getClass().getDeclaredFields();
            for (Field f : fields) {
                f.setAccessible(true);
            }
            // 输出finalHeader的所有属性
            // //System.out.println("=============About
            // finalHeader===============");
            for (Field f : fields) {
                String field = f.toString().substring(f.toString().lastIndexOf(".") + 1); // 取出属性名称
                try {
                    System.out.println("finalHeader." + field + " --> " + f.get(row));
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    logger.error("AutoLoadProject捕获异常: ",e);
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    logger.error("AutoLoadProject捕获异常: ",e);
                }
            }
        }
        // opty-prod-table
    }

    public static void ReadAllJSPFileAndGetModel() throws DocumentException {
        Init();
        // jspfile =
        // "C://app/workspace/java/link-crm/src/main/webapp/portal/opty/";
        List<String> lstFileNames = getListFiles(jspfile, "jsp", true);
        for (int i = 0; i < lstFileNames.size(); i++) {
            String temp = lstFileNames.get(i);
            // //System.out.println(temp);
            // if (!temp.contains("optyDetail.jsp")) {
            // continue;
            // }
            String content = readFileByLines(temp);
            if (content.contains("hdatagrid")) {
                Map<String, String> tableinfo = new HashMap<String, String>();
                Map<String, String> tableinfoKey = new HashMap<String, String>();
                tableinfo = gertable(content);
                tableinfoKey = gettableKeyword(content);
                Iterator it = tableinfo.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry entry = (Map.Entry) it.next();
                    Object key = entry.getKey();
                    Object value = entry.getValue();
                    String tableName = key.toString();
                    String tableVaue = value.toString();
                    logger.info("we get table:" + temp + "," + tableName);
                    List<LnkInnerField> rows = gerFieldInfo(tableVaue);
                    jspModelInfo.put(temp + "," + tableName, rows);
                    if (tableinfoKey.containsKey(tableName)) {
                        jspModelKeyword.put(temp + "," + tableName, tableinfoKey.get(tableName));
                        LnkInnerObject headerrows = new LnkInnerObject();
                        headerrows.setAttr06(temp);// jsp路径
                        headerrows.setAttr08(tableName);// jsp table
                        headerrows.setAttr09(tableinfoKey.get(tableName));
                        finalHeader.add(headerrows);
                    } else {
                        LnkInnerObject headerrows = new LnkInnerObject();
                        headerrows.setAttr06(temp);// jsp路径
                        headerrows.setAttr08(tableName);// jsp table
                        headerrows.setAttr09("");// key
                        // info
                        finalHeader.add(headerrows);
                    }
                    // tn++;
                }
                logger.info("start out put for tableinfoKey" + temp);
                it = tableinfoKey.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry entry = (Map.Entry) it.next();
                    Object key = entry.getKey();
                    Object value = entry.getValue();
                    String tableName = key.toString();
                    String tableVaue = value.toString();
                    logger.info(tableName + "---" + tableVaue);
                }
                logger.info("end out put for tableinfoKey");
            }
        }
        // if (1 == 1) {
        // return;
        // }
        // System.out.println("分析内容。获取更多信息。");
        // 分析内容。获取更多信息。
        // printHeader();
        for (LnkInnerObject row : finalHeader) {
            String keyword = row.getAttr09();
            if (keyword == null || !keyword.contains("/")) {
                // //System.out.println("continue");
                continue;
            }
            // if (!"attachment-table".equals(row.getAttr08())) {
            // continue;
            // }
            // System.out.println(row.getAttr06());
            // String user = GetModelFrompath(modelpath);
            int kn = keyword.indexOf("/");
            String key1 = keyword.substring(0, kn);
            String key2 = keyword.substring(keyword.indexOf("/"), keyword.length());
            lstFileNames = getListFiles(Folder, "java", true);
            for (int i = 0; i < lstFileNames.size(); i++) {
                String temp = lstFileNames.get(i);
                // if (!temp.contains("LnkInnerFieldController.java")) {
                // continue;
                // }
                String content = readFileByLines(temp).replace("<Filter>", "");
                if (content.contains("@Controller")) {
                    // System.out.println("to here");
                    if (content.contains("portal/" + key1 + "\")")) {
                        // System.out.println("to here2");
                        String outModel = "";
                        String servicealias = "";
                        String servicemethod = "";
                        String service = "";
                        if (content.contains(key2)) {
                            // System.out.println("to here3");
                            // System.out.println(key2);
                            // System.out.println(temp);
                            // System.out.println(Content);
                            Pattern p1 = Pattern.compile(
                                    "@RequestMapping\\([\\s\\S]*?\"" + key2
                                            + "\"[\\s\\S]*?List<([\\S]*?)>[\\s\\S]*?=[\\s]*?([\\S]*?)"
                                            + "\\.([\\S]*?\\(qps\\));[\\s\\S]*?return",
                                    Pattern.MULTILINE);
                            Matcher m1 = p1.matcher(content);
                            boolean find = m1.find();
                            if (!find) {
                                // System.out.println("to here4---1");
                                // System.out.println(key2);
                                Pattern p2 = Pattern.compile(
                                        "@RequestMapping\\([\\s\\S]*?\"" + key2
                                                + "/[\\s\\S]*?List<([\\S]*?)>[\\s\\S]*?=[\\s]*?([\\S]*?)"
                                                + "\\.([\\S]*?\\(qps\\));[\\s\\S]*?return",
                                        Pattern.MULTILINE);
                                m1 = p2.matcher(content);
                                find = m1.find();
                                if (!find) {
                                    // System.out.println("to here4---2");
                                    // System.out.println(key2);
                                    p2 = Pattern.compile(
                                            "@RequestMapping\\([\\s\\S]*?\"" + key2
                                                    + "\"[\\s\\S]*?List<([\\S]*?)>[\\s\\S]*?=[\\s]*?([\\S]*?)"
                                                    + "\\.([\\S]*?\\(record\\));[\\s\\S]*?return",
                                            Pattern.MULTILINE);
                                    m1 = p2.matcher(content);
                                    find = m1.find();
                                    if (!find) {
                                        // System.out.println("to here4---3");
                                        // System.out.println(key2);
                                        p2 = Pattern.compile(
                                                "@RequestMapping\\([\\s\\S]*?\"" + key2
                                                        + "/[\\s\\S]*?List<([\\S]*?)>[\\s\\S]*?=[\\s]*?([\\S]*?)"
                                                        + "\\.([\\S]*?\\(record\\));[\\s\\S]*?return",
                                                Pattern.MULTILINE);
                                        m1 = p2.matcher(content);
                                        find = m1.find();
                                    }
                                }
                            }
                            if (find) {
                                // System.out.println("to here4");
                                if (m1.groupCount() > 2) {
                                    outModel = m1.group(1);
                                    servicealias = m1.group(2);
                                    servicemethod = m1.group(3);
                                    servicemethod = servicemethod.replaceAll("\\([\\s\\S]*?\\)", "");
                                    // System.out.println("get fuck var");
                                    // System.out.println(outModel);
                                    // System.out.println(servicealias);
                                    // System.out.println(servicemethod);
                                    if ("getBasicService()".equals(servicealias)) {
                                        Pattern p3 = Pattern.compile(
                                                "public[\\s]+BasicService[\\s]*?<([\\s\\S]*?)>[\\s]+"
                                                        + "getBasicService[\\s\\S]*?return[\\s]+([\\S]*?)[\\s]*;",
                                                Pattern.MULTILINE);
                                        Matcher m3 = p3.matcher(content);
                                        if (m3.find()) {
                                            // //System.out.println("to
                                            // here63");
                                            if (m3.groupCount() > 0) {
                                                outModel = m3.group(1).trim();
                                                servicealias = m3.group(2).trim();
                                                // servicemethod = key2;
                                                Pattern p4 = Pattern.compile(
                                                        "private[\\s]*?([\\S]*?)[\\s]*?" + servicealias + "[\\s]*?;",
                                                        Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                                                Matcher m4 = p4.matcher(content);
                                                if (m4.find()) {
                                                    // //System.out.println("to
                                                    // here7");
                                                    if (m4.groupCount() > 0) {
                                                        service = m4.group(1);
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        Pattern p2 = Pattern.compile(
                                                "private[\\s]*?([\\S]*?)[\\s]*?" + servicealias + "[\\s]*?;",
                                                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                                        Matcher m2 = p2.matcher(content);
                                        if (m2.find()) {
                                            if (m2.groupCount() > 0) {
                                                service = m2.group(1);
                                            }
                                        }
                                    }
                                }
                            }
                        } // end key2
                        if ("".equals(outModel) && content.contains("BasicController")) {
                            // //System.out.println("to here5");
                            Pattern p1 = Pattern.compile(
                                    "public[\\s]+BasicService[\\s]*?<([\\s\\S]*?)>[\\s]+"
                                            + "getBasicService[\\s\\S]*?return[\\s]+([\\S]*?)[\\s]*;",
                                    Pattern.MULTILINE);
                            Matcher m1 = p1.matcher(content);
                            if (m1.find()) {
                                // //System.out.println("to here6");
                                if (m1.groupCount() > 0) {
                                    outModel = m1.group(1).trim();
                                    servicealias = m1.group(2).trim();
                                    servicemethod = key2;
                                    Pattern p2 = Pattern.compile(
                                            "private[\\s]*?([\\S]*?)[\\s]*?" + servicealias + "[\\s]*?;",
                                            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                                    Matcher m2 = p2.matcher(content);
                                    if (m2.find()) {
                                        // //System.out.println("to here7");
                                        if (m2.groupCount() > 0) {
                                            service = m2.group(1);
                                        }
                                    }
                                }
                            }
                        }
                        row.setName(outModel);
                        row.setAttr05(getModelPathFrommodelName(outModel));
                        row.setBasetablealais("T1");
                        row.setNewflag("Y");
                        row.setUpdateflag("Y");
                        row.setDeleteflag("Y");
                        row.setQueryflag("Y");
                        row.setOrderbyfield("T1.CREATED DESC");
                        row.setAttr04("com.link.portal");
                        row.setActiveflag("Y");
                        row.setAttr11(service);
                        servicemethod = servicemethod.replace("/", "");
                        row.setAttr12(servicemethod);
                        Map<String, String> xmlInfo = GetsqlFromServiceAndmethod(service, servicemethod);
                        row.setAttr13(xmlInfo.get("serviceimpl"));
                        row.setAttr14(xmlInfo.get("MapperName"));
                        row.setAttr15(xmlInfo.get("MapperId"));
                        row.setAttr07(xmlInfo.get("MappperXMLPath"));
                        String controllerFilePath = temp;
                        row.setAttr17(controllerFilePath);
                        TempInsertTable = "";
                        String sql = getsqlFromMapperId(row.getAttr07(), row.getAttr15());
                        row.setBasetable(TempInsertTable);
                        break;
                    }
                }
            }
        }
        // printHeader();
    }

    private static String TempInsertTable;

    private static final Pattern PATTERN11 = Pattern.compile("INSERT[\\s]+INTO[\\s]+([\\S]*?)[\\s]+",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static final Pattern PATTERN12 = Pattern.compile("<include refid=\"([\\S]*?)\"/>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static String getsqlFromMapperId(String path, String mapperid) throws DocumentException {
        if (path == null || "".equals(path)) {
            return "";
        }
        if (mapperid == null || "".equals(mapperid)) {
            return "";
        }
        Map<String, String> sqlinfo = new HashMap<String, String>();
        String sql = "";
        TempInsertTable = "";
        SAXReader reader = new SAXReader();
        File file = new File(path);
        Document document = reader.read(file);
        Element root = document.getRootElement();
        List<Element> childElements = root.elements();
        for (Element child : childElements) {
            String id = child.attributeValue("id");
            String value = child.getText() + System.getProperty("line.separator");
            List<Element> elementList = child.elements();
            for (Element ele : elementList) {
                value += ele.asXML() + System.getProperty("line.separator");
            }
            sqlinfo.put(id, value);
            // System.out.println(Id);
            // System.out.println(Value);
            if (id.contains("Insert") || id.contains("insert")) {
                // //System.out.println("-------------------------------------------------------------");
//                Pattern p1 = Pattern.compile("INSERT[\\s]+INTO[\\s]+([\\S]*?)[\\s]+",
//                        Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                Matcher m1 = PATTERN11.matcher(value);
                if (m1.find()) {
                    // //System.out.println("fond" + m1.group(0));
                    if (m1.groupCount() > 0) {
                        TempInsertTable = m1.group(1);
                        TempInsertTable = TempInsertTable.replaceAll("\\([\\s\\S]*", "");
                        // System.out.println("table: " + TempInsertTable);
                    }
                }
            }
        }
        Iterator it = sqlinfo.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            String name = key.toString();
            String txt = value.toString();
            if (name.equals(mapperid)) {
                if (txt.contains("include")) {
//                    Pattern p2 = Pattern.compile("<include refid=\"([\\S]*?)\"/>",
//                            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                    Matcher m2 = PATTERN12.matcher(txt);
                    while (m2.find()) {
                        if (m2.groupCount() > 0) {
                            String tmpid = m2.group(1);
                            txt = txt.replace("<include refid=\"" + tmpid + "\"/>", sqlinfo.get(tmpid));
                        }
                    }
                    sql = txt;
                }
                sql = txt;
            }
        }
        return sql;
    }

    private static Map<String, String> GetsqlFromServiceAndmethod(String service, String servicemethod) {
        String serviceimpl = "";
        String mapperAlias = "";
        String mapperId = "";
        String mapperName = "";
        String mappperXMLPath = "";
        String basePath = "";
        // System.out.println("find xml");
        List<String> lstFileNames = getListFiles(Folder, "java", true);
        for (int i = 0; i < lstFileNames.size(); i++) {
            String temp = lstFileNames.get(i);
            String temp1 = temp.replace("\\", "/");
            if (temp1.contains("/" + service + "Impl.java")) {
                serviceimpl = temp;
                basePath = temp1.replace("/service/" + service + "Impl.java", "") + "/";
            }
            if (temp1.contains("/" + service + "Imp.java")) {
                serviceimpl = temp;
                basePath = temp1.replace("/service/" + service + "Imp.java", "") + "/";
            }
        }
        // System.out.println(serviceimpl);
        // System.out.println(BasePath);
        // System.out.println(serviceimpl);
        if (!"".equals(serviceimpl)) { // foundImplFile
            String content = readFileByLines(serviceimpl);
            Pattern p1 = Pattern.compile(servicemethod + "[\\s\\S]*?return[\\s]*([\\S]*?)\\.([\\S]*?)\\([\\S\\s]*?\\);",
                    Pattern.MULTILINE);
            Matcher m1 = p1.matcher(content);
            while (m1.find()) {
                if (m1.groupCount() > 1) {
                    mapperAlias = m1.group(1);
                    mapperId = m1.group(2);
                }
            }
            Pattern p2 = Pattern.compile("private[\\s]*?([\\S]*?)[\\s]*?" + mapperAlias + "[\\s]*?;",
                    Pattern.MULTILINE);
            Matcher m2 = p2.matcher(content);
            while (m2.find()) {
                if (m2.groupCount() > 0) {
                    mapperName = m2.group(1);
                }
            }
            if ("".equals(mapperName) && content.contains("extends BasicServiceImpl")) {
                String tempMapperAlias = "";
                // System.out.println("to here15");
                p1 = Pattern.compile(
                        "public[\\s]+BasicMapper[\\s]*?<([\\s\\S]*?)>[\\s]+"
                                + "getBasicMapper[\\s\\S]*?return[\\s]+([\\S]*?)[\\s]*;",
                        Pattern.MULTILINE);
                m1 = p1.matcher(content);
                if (m1.find()) {
                    // //System.out.println("to here6");
                    if (m1.groupCount() > 0) {
                        // outModel = m1.group(1).trim();
                        tempMapperAlias = m1.group(2).trim();
                        // servicemethod = key2;
                        p2 = Pattern.compile("private[\\s]*?([\\S]*?)[\\s]*?" + tempMapperAlias + "[\\s]*?;",
                                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                        m2 = p2.matcher(content);
                        if (m2.find()) {
                            // //System.out.println("to here7");
                            if (m2.groupCount() > 0) {
                                mapperName = m2.group(1);
                                mapperId = servicemethod;
                            }
                        }
                    }
                }
            }
            if ("".equals(mapperName)) {
                p1 = Pattern.compile(
                        servicemethod + "[\\s\\S]*?[\\s]*([\\S]*?)\\.([\\S]*?)\\([\\S\\s]*?\\);[\\S\\s]*?return",
                        Pattern.MULTILINE);
                m1 = p1.matcher(content);
                while (m1.find()) {
                    if (m1.groupCount() > 1) {
                        mapperAlias = m1.group(1).trim();
                        mapperId = m1.group(2);
                    }
                }
                if (mapperAlias.contains("=")) {
                    mapperAlias = mapperAlias.replaceAll("[\\s\\S]*?=", "");
                }
                p2 = Pattern.compile("private[\\s]*?([\\S]*?)[\\s]*?" + mapperAlias + "[\\s]*?;", Pattern.MULTILINE);
                m2 = p2.matcher(content);
                while (m2.find()) {
                    if (m2.groupCount() > 0) {
                        mapperName = m2.group(1);
                    }
                }
            }
        }
        // System.out.println("mapper info is:");
        // System.out.println(MapperAlias);
        // System.out.println(MapperName);
        // System.out.println(MapperId);
        if (!"".equals(mapperName) && !"".equals(mapperId)) {
            // BasePath
            // lstFileNames = getListFiles(Folder, "xml", true);
            lstFileNames = getListFiles(basePath, "xml", true);
            for (int i = 0; i < lstFileNames.size(); i++) {
                String temp = lstFileNames.get(i);
                if (temp.contains("MySql")) {
                    continue;
                }
                String content1 = readFileByLines(temp);
                if (content1.contains(mapperName) && content1.contains(mapperId)) {
                    mappperXMLPath = temp;
                }
            }
        }
        Map<String, String> xmlInfo = new HashMap<String, String>();
        xmlInfo.put("serviceimpl", serviceimpl);
        xmlInfo.put("MapperAlias", mapperAlias);
        xmlInfo.put("MapperId", mapperId);
        xmlInfo.put("MapperName", mapperName);
        xmlInfo.put("MappperXMLPath", mappperXMLPath);
        return xmlInfo;
    }

    private static String getModelPathFrommodelName(String modelName) {
        String out = "";
        List<String> lstFileNames = getListFiles(Folder, "java", true);
        for (int i = 0; i < lstFileNames.size(); i++) {
            String temp = lstFileNames.get(i);
            String temp1 = temp.replace("\\", "/");
            if (temp1.contains("/" + modelName + ".java")) {
                out = temp;
            }
        }
        return out;
    }

    public static void getAllModelInfoToTable() {
        GetAllModel(Folder);
    }

    /**
     * 通过传入的各配置文件路径，解析出最终的内容。
     */
    public static void GetJspAllFileInfo(String modelFilesp, String jspFilesp, String jspTablesp, String xmlfilesp,
                                         String xmlMapperId) throws DocumentException {
        Init();// 初始化
        List<String> lstFileNames = getListFiles(Folder, "java", true);
        for (int i = 0; i < lstFileNames.size(); i++) {
            String temp = lstFileNames.get(i);
            if (temp.contains("BasicModel.java")) {
                List<LnkInnerField> tf = getallField(temp);
                for (int k = 0; k < tf.size(); k++) {
                    basemodelinfo.put(tf.get(k).getName(), tf.get(k).getFieldtype());// 获得basemodel的信息
                }
            }
        }
        GetOneJspFileInfo(jspFilesp);// 获得jsp文件的字段信息
        GetOneModel(modelFilesp);// 获得model的信息
        String temp = getsqlFromMapperId(xmlfilesp, xmlMapperId);
        ParseSQL(temp);// 分析sql文件
        Iterator it = modelInfo.entrySet().iterator();// 针对model的信息和jsp的信息进行融合。得到最终的信息。
        // 以下对象实际上应该只会返回一条记录
        if (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            List<LnkInnerField> lf = (List<LnkInnerField>) value;
            Iterator it1 = jspModelInfo.entrySet().iterator();
            boolean fund = false;
            while (it1.hasNext()) {
                Map.Entry entry1 = (Map.Entry) it1.next();
                Object key1 = entry1.getKey();
                Object value1 = entry1.getValue();
                List<LnkInnerField> lf2 = (List<LnkInnerField>) value1;
                if ((jspFilesp + "," + jspTablesp).equals(key1.toString())) {
                    MergeFinalField(lf, lf2);
                    fund = true;
                    System.out.println("mergeFinalField");
                }
            }
        }
        // finalLF
        // 读写xml的配置，获得更多信息和link关系。
    }

    private static void MergeFinalField(List<LnkInnerField> lf, List<LnkInnerField> lf2) {
        for (int i = 0; i < lf.size(); i++) { // 针对model的字段。
            LnkInnerField row1 = lf.get(i);
            // LnkInnerField row = new LnkInnerField();
            String fname = row1.getName();
            // System.out.println(fname);
            boolean fund = false;
            for (int j = 0; j < lf2.size(); j++) {
                LnkInnerField row2 = lf2.get(j);
                String lname = row2.getName();
                if (lname == null) {
                    continue;
                }
                if (fname.equals(lname)) {
                    // System.out.println(row2.getDisplayname());
                    row2.setFieldtype(row1.getFieldtype());
                    if (sql_field.containsKey(lname.toUpperCase())) {
                        String col = sql_field.get(lname.toUpperCase());
                        String coltb = "";
                        String coln = "";
                        if (col.contains(".")) {
                            coltb = col.substring(0, col.indexOf(".")).replace(".", "");
                            coln = col.substring(col.indexOf("."), col.length()).replace(".", "");
                            row2.setColumnname(coln);
                            if ("T1".equals(coltb)) {
                                row2.setJoinname("");
                            } else {
                                row2.setJoinname(coltb + "_" + sql_tbmap.get(coltb));
                            }
                        } else {
                            row2.setColumnname(col);
                            row2.setJoinname("");
                        }
                    }
                    fund = true;
                    finalLF.add(row2);
                }
            }
            if (!fund) {
                finalLF.add(row1);
            }
        }
        Iterator it = basemodelinfo.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            String fname = key.toString();
            for (int j = 0; j < lf2.size(); j++) {
                LnkInnerField row2 = lf2.get(j);
                String lname = row2.getName();
                if (lname == null) {
                    continue;
                }
                if (fname.equals(lname)) {
                    row2.setFieldtype(value.toString());
                    if (sql_field.containsKey(lname.toUpperCase())) {
                        String col = sql_field.get(lname.toUpperCase());
                        String coltb = "";
                        String coln = "";
                        if (col.contains(".")) {
                            coltb = col.substring(0, col.indexOf(".")).replace(".", "");
                            coln = col.substring(col.indexOf("."), col.length()).replace(".", "");
                            row2.setColumnname(coln);
                            if ("T1".equals(coltb)) {
                                row2.setJoinname("");
                            } else {
                                row2.setJoinname(coltb + "_" + sql_tbmap.get(coltb));
                            }
                        } else {
                            row2.setColumnname(col);
                            row2.setJoinname("");
                        }
                    }
                    finalLF.add(row2);
                }
            }
        }
    }

    private static int Mappingeach(List<LnkInnerField> lf, List<LnkInnerField> lf2) {
        Boolean isMapping = true;
        int count = 0;
        for (int i = 0; i < lf2.size(); i++) {
            Boolean childmap = false;
            String fieldname = lf2.get(i).getName();
            if (basemodelinfo.containsKey(fieldname)) {
                count++;
                childmap = true;
            } else {
                for (int k = 0; k < lf.size(); k++) {
                    String fieldname2 = lf.get(k).getName();
                    if (fieldname2.equals(fieldname)) {
                        count++;
                        childmap = true;
                    }
                }
            }
            if (!childmap) {
                isMapping = false;
            }
        }
        return count;
    }

    private static final Pattern PATTERN13 = Pattern.compile("model/([\\S]*?).java", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    public static String GetModelFrompath(String path) {
        // //////System.out.println(path);
        String model = "";
        path = path.replace("\\", "/");
//        Pattern p1 = Pattern.compile("model/([\\S]*?).java", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher m1 = PATTERN13.matcher(path);
        while (m1.find()) {
            if (m1.groupCount() > 0) {
                model = m1.group(1);
            }
        }
        // //////System.out.println("user is:" + user);
        return model;
    }

    private static Boolean CheckMappingFiel(String jspFilename, String Keyword, String modelpath) {
        Boolean isCheckMapping = false;
        return isCheckMapping;
    }

    private static void printjspTable() {
        Iterator it = jspModelInfo.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            String tableName = key.toString();
            // System.out.println(tableName);
        }
        // System.out.println("--------------end----------------");
    }

    private static void printModel() {
        Iterator it = modelInfo.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            String tableName = key.toString();
            String model = GetModelFrompath(tableName);
            // System.out.println(tableName + "," + user);
        }
        // System.out.println("--------------end----------------");
    }

    private static void MappingAndMergeField() {
        Iterator it1 = jspModelInfo.entrySet().iterator();
        List<LnkInnerField> last = null;
        String lasttableName = "";
        int sn = 0;
        while (it1.hasNext()) {
            Map.Entry entry1 = (Map.Entry) it1.next();
            Object key1 = entry1.getKey();
            Object value1 = entry1.getValue();
            String tableName1 = key1.toString();
            Iterator it = modelInfo.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                String tableName = key.toString();
                Boolean isCheckMapping = CheckMappingFiel(tableName1, jspModelKeyword.get(tableName1), tableName);
                if (isCheckMapping) {
                    // System.out.println("------------------------------");
                    // System.out.println(tableName1);
                    // System.out.println(jspModelKeyword.get(tableName1));
                    // System.out.println(tableName);
                    // System.out.println("--------------end----------------");
                    break;
                }
            }
        }
    }

    private static void GetOneJspFileInfo(String path) {
        String temp = path;
        String content = readFileByLines(temp);
        if (content.contains("hdatagrid")) {
            Map<String, String> tableinfo = new HashMap<String, String>();
            Map<String, String> tableinfoKey = new HashMap<String, String>();
            tableinfo = gertable(content);
            tableinfoKey = gettableKeyword(content);
            Iterator it = tableinfo.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                String tableName = key.toString();
                String tableVaue = value.toString();
                List<LnkInnerField> rows = gerFieldInfo(tableVaue);
                jspModelInfo.put(temp + "," + tableName, rows);
                if (tableinfoKey.containsKey(tableName)) {
                    jspModelKeyword.put(temp + "," + tableName, tableinfoKey.get(tableName));
                }
            }
        }
    }

    private static void GetAllJspFileInfo(String path) {
    }

    private static List<LnkInnerField> GetALlJSpFiled(String filename) {
        List<LnkInnerField> rows = new ArrayList<LnkInnerField>();
        return rows;
    }

    public static List<String> getListFiles(String path, String suffix, boolean isdepth) {
        List<String> lstFileNames = new ArrayList<String>();
        File file = new File(path);
        return listFile(lstFileNames, file, suffix, isdepth);
    }

    private static List<String> listFile(List<String> lstFileNames, File file, String suffix, boolean isdepth) {
        // 若是目录, 采用递归的方法遍历子目录
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (isdepth || files[i].isFile()) {
                    listFile(lstFileNames, files[i], suffix, isdepth);
                }
            }
        } else {
            String filePath = file.getAbsolutePath();
            if (!"".equals(suffix)) {
                int begIndex = filePath.lastIndexOf("."); // 最后一个.(即后缀名前面的.)的索引
                String tempsuffix = "";
                if (begIndex != -1) {
                    tempsuffix = filePath.substring(begIndex + 1, filePath.length());
                    if (tempsuffix.equals(suffix)) {
                        lstFileNames.add(filePath);
                    }
                }
            } else {
                lstFileNames.add(filePath);
            }
        }
        return lstFileNames;
    }

    private static void GetOneModel(String folder) {
        String temp = folder;
        String Content = readFileByLines(temp);
        if (Content.contains("extends BasicModel")) {
            modelInfo.put(temp, getallField(temp));
            // //////////System.out.println(temp);
        }
    }

    private static void GetAllModel(String folder) {
        List<String> lstFileNames = getListFiles(folder, "java", true);
        for (int i = 0; i < lstFileNames.size(); i++) {
            String temp = lstFileNames.get(i);
            if (temp.contains("BasicModel.java")) {
                List<LnkInnerField> tf = getallField(temp);
                for (int k = 0; k < tf.size(); k++) {
                    basemodelinfo.put(tf.get(k).getName(), tf.get(k).getFieldtype());
                }
            } else {
                String content = readFileByLines(temp);
                if (content.contains("extends BasicModel")) {
                    modelInfo.put(temp, getallField(temp));
                    // //////////System.out.println(temp);
                }
            }
        }
    }

    private static final Pattern PATTERN14 = Pattern.compile("private\\s*([\\S]*)\\s*([\\S]*)\\s*;",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static List<LnkInnerField> getallField(String filename) {
        List<LnkInnerField> rows = new ArrayList<LnkInnerField>();
        String content = readFileByLines(filename);
//        Pattern p1 = Pattern.compile("private\\s*([\\S]*)\\s*([\\S]*)\\s*;",
//                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher m1 = PATTERN14.matcher(content);
        while (m1.find()) {
            if (m1.groupCount() > 1) {
                LnkInnerField field = new LnkInnerField();
                field.setName(m1.group(2));
                field.setFieldtype(m1.group(1));
                rows.add(field);
            }
        }
        return rows;
    }

    private static final Pattern PATTERN15 =
            Pattern.compile("data-filter-filed=\"([\\S]*)\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static final Pattern PATTERN16 =
            Pattern.compile("url:'/action/link/basic/list/([\\S]*?)'",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static final Pattern PATTERN17 = Pattern.compile("url:'/action/link/basic/list/([\\S]*?)'",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static List<LnkInnerField> gerFieldInfo(String txt) {
        Map<String, String> keyfiltermap = new HashMap<String, String>();
//        Pattern p0 = Pattern.compile("data-filter-filed=\"([\\S]*)\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher m0 = PATTERN15.matcher(txt);
        while (m0.find()) {
            keyfiltermap.put(m0.group(1), "");
        }
        List<LnkInnerField> rows = new ArrayList<LnkInnerField>();
//        Pattern p1 = Pattern.compile("<th[^>]*field=\"([\\S]*)\"[^>]*?>([\\s\\S]*?)</th>",
//                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher m1 = PATTERN16.matcher(txt);
        while (m1.find()) {
            String fileth = m1.group(0).toLowerCase();
            String filethold = m1.group(0);
            if (m1.groupCount() > 1) {
                LnkInnerField field = new LnkInnerField();
                field.setName(m1.group(1));
                field.setDisplayname(m1.group(2));
                if (fileth.contains("textbox")) {
                    field.setUitype("textbox");
                } else if (fileth.contains("combobox")) {
                    field.setUitype("combobox");
//                    Pattern p2 = Pattern.compile("url:'/action/link/basic/list/([\\S]*?)'",
//                            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                    Matcher m2 = PATTERN17.matcher(filethold);
                    while (m2.find()) {
                        String lovType = m2.group(1);
                        field.setLovtype(lovType);
                    }
                } else if (fileth.contains("validatebox")) {
                    field.setUitype("validatebox");
                } else if (fileth.contains("checkbox")) {
                    field.setUitype("checkbox");
                } else if (fileth.contains("'datebox'")) {
                    field.setUitype("datebox");
                } else if (fileth.contains("datetimebox")) {
                    field.setUitype("datetimebox");
                } else {
                    field.setUitype("validatebox");
                }
                if (fileth.contains("required:true")) {
                    field.setUirequired("Y");
                } else {
                    field.setUirequired("N");
                }
                if (fileth.contains("hiden")) {
                    field.setAttr01("Y");
                } else {
                    field.setAttr01("N");
                }
                if (fileth.contains("defaultSearch=\"true\"")) {
                    field.setQueryflag("Y");
                } else {
                    field.setAttr01("N");
                }
                String thisFieldName = m1.group(1);
                if (keyfiltermap.containsKey(thisFieldName)) {
                    field.setAttr03("Y");
                }
                field.setQueryflag("Y");
                field.setOrderflag("Y");
                field.setActiveflag("Y");
                field.setUpdateflag("Y");
                field.setAttr02("Y");
                field.setInsertflag("Y");
                field.setCalcflag("N");
                field.setUireadonly("N");
                rows.add(field);
            }
        }
        if (rows.size() > 0) {
            return rows;
        } else {
            // //////System.out.println("字段太少，不可参照");
            return new ArrayList<LnkInnerField>();
        }
    }

    private static final Pattern PATTERN18 = Pattern.compile("<table[^>]*id=\"([\\S]*)\"[^>]*?>([\\s\\S]*?)</table>",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static Map<String, String> gertable(String txt) {
        Map<String, String> tableinfo = new HashMap<String, String>();
//        Pattern p1 = Pattern.compile("<table[^>]*id=\"([\\S]*)\"[^>]*?>([\\s\\S]*?)</table>",
//                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        Matcher m1 = PATTERN18.matcher(txt);
        while (m1.find()) {
            if (m1.groupCount() > 1) {
                tableinfo.put(m1.group(1), m1.group(2));
            }
        }
        return tableinfo;
    }

    private static final Pattern PATTERN19 = Pattern.compile("\\$([\\S]+?)[\\s]*?=[\\s]*?\\$\\('#([\\S]+?)'\\)[\\s]*?;",
            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static final Pattern PATTERN20 = Pattern.compile(
            "\\$([\\S]+?)[\\s]*?.hdatagrid[\\s\\S]*?url[\\s]*?:[\\s]?['|\"]/action/link/([\\S]*?)['|\"]", Pattern.MULTILINE);

    private static Map<String, String> gettableKeyword(String txt) {
        txt = txt.replace("${AppContext.ctxPath}", "");
        Map<String, String> tableinfo = new HashMap<String, String>();
        Pattern p1 = PATTERN19;/*Pattern.compile("\\$([\\S]+?)[\\s]*?=[\\s]*?\\$\\('#([\\S]+?)'\\)[\\s]*?;",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);*/
        // //System.out.println(txt);
        Matcher m1 = p1.matcher(txt);
        while (m1.find()) {
            if (m1.groupCount() > 1) {
                String sName = m1.group(1).trim();
                String sId = m1.group(2).trim();
                Pattern p2 = Pattern.compile(
                        sName
                                + "[\\s]*?.hdatagrid\\(\\{[\\s\\S]*?url[\\s]*?:[\\s]"
                                + "?['|\"]/action/link/([\\S]*?)['|\"]",
                        Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
                Matcher m2 = p2.matcher(txt);
                if (m2.find()) {
                    // System.out.println(m2.group(0));
                    if (m2.groupCount() > 0) {
                        String temp = m2.group(1).trim();
                        temp = temp.replaceAll("/$", "");
                        tableinfo.put(sId, temp);
                    }
                }
            }
        }
        if (tableinfo.size() == 0) {
            p1 = PATTERN20;/*Pattern.compile(
                    "\\$([\\S]+?)[\\s]*?.hdatagrid[\\s\\S]*?url[\\s]*?:[\\s]?['|\"]/action/link/([\\S]*?)['|\"]",
                    Pattern.MULTILINE);*/
            m1 = p1.matcher(txt);
            while (m1.find()) {
                if (m1.groupCount() > 1) {
                    String sName = m1.group(1).trim();
                    sName = sName.replace("#", "");
                    sName = sName.replace("'", "");
                    sName = sName.replace("(", "");
                    sName = sName.replace(")", "");
                    String sId = m1.group(2).trim();
                    tableinfo.put(sName, sId);
                }
            }
        }
        return tableinfo;
    }

    public static String readFileByLines(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            return "";
        }
        String fileContent = "";
        try (FileInputStream fis = new FileInputStream(fileName);
             InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
             BufferedReader br = new BufferedReader(isr)) {
            String line = null;
            while ((line = br.readLine()) != null) {
                fileContent += line;
                fileContent += "\r\n"; // 补上换行符
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("AutoLoadProject捕获异常: ",e);
        }
        Map<String, String> patterns = new HashMap<String, String>();
        patterns.put("([^:])\\/\\/.*", "$1");// 匹配在非冒号后面的注释，此时就不到再遇到http://
        patterns.put("\\s+\\/\\/.*", "");// 匹配“//”前是空白符的注释
        patterns.put("^\\/\\/.*", "");
        patterns.put("^\\/\\*\\*.*\\*\\/$", "");
        patterns.put("\\/\\*.*\\*\\/", "");
        patterns.put("/\\*(\\s*\\*\\s*.*\\s*?)*\\*\\/", "");
        // patterns.put("/\\*(\\s*\\*?\\s*.*\\s*?)*", "");
        Iterator<String> keys = patterns.keySet().iterator();
        String key = null;
        String value = "";
        while (keys.hasNext()) {
            // 经过多次替换
            key = keys.next();
            value = patterns.get(key);
            fileContent = replaceAll(fileContent, key, value);
        }
        fileContent = fileContent.replaceAll("/\\*[\\s\\S]*?\\*/", "");
        // FileContent = FileContent.replaceAll("//[\\s\\S]*?$", "");
        return fileContent;
    }

    public static String replaceAll(String fileContent, String patternString, String replace) {
        String str = "";
        Matcher matcher = null;
        Pattern pattern = null;
        try {
            pattern = Pattern.compile(patternString);
            matcher = pattern.matcher(fileContent);
            str = matcher.replaceAll(replace);
        } catch (Exception e) {
            logger.error("AutoLoadProject捕获异常: ",e);
        } finally {
            matcher = null;
            pattern = null;
        }
        // 获得匹配器对象
        return str;
    }
}
